package com.qidian.buy.service.impl;

import com.qidian.buy.service.ItemService;
import com.qidian.buy.util.pojo.QdResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/14 11:44
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FreeMarkerConfigurer configurer;
    @Value("${static-path}")
    private String staticPath;
    @Value("${manager-service-name}")
    private String managerServiceName;
    @Override
    public QdResult genDetailStatic(Long itemId) {
        // 远程调用加载详情信息
        QdResult result = restTemplate.getForObject("http://" + managerServiceName + "/item/get/" + itemId, QdResult.class);
        // 处理图片
        LinkedHashMap item = (LinkedHashMap) result.getData();
        // 处理图片  item中需要images存储所有的图片
        List<String> images = new ArrayList<>();
        String image = item.get("image").toString();
        images.addAll(Arrays.asList(image.split(";")));
        item.put("images",images);
        // 准备一个Map
        Map data = new HashMap();
        data.put("item",item);
        //  调用模版生成静态页面
        Configuration configuration = configurer.getConfiguration();
        try {
            // 获取模版
            Template template = configuration.getTemplate("page.ftlh");
            // 准备输出流
            Writer writer = new FileWriter(staticPath+"\\"+item.get("itemId")+".html");
            // 执行模版
            template.process(data,writer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
        return QdResult.ok();
    }
}
